package com.example.docker.controller;


import com.example.docker.entity.ApiRequest;
import com.example.docker.entity.ChatMessage;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Controller
public class ChatController {

    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private final RestTemplate restTemplate;

    @Autowired
    public ChatController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/chat")
    public String index(Model model, HttpSession session) {
        if (session.getAttribute("messages") == null) {
            session.setAttribute("messages", new ArrayList<ChatMessage>());
        }
        return "chat";
    }

    @PostMapping("/chat")
    public String chat(@RequestParam String userInput,
                       HttpSession session,
                       Model model) {

        List<ChatMessage> history = (List<ChatMessage>) session.getAttribute("messages");

        // 构建API请求
        ApiRequest request = new ApiRequest();
        request.setModel("deepseek-chat");
        request.setStream(false);

        List<ChatMessage> messages = new ArrayList<>();
        messages.add(new ChatMessage("system", "You are a helpful assistant."));
        messages.add(new ChatMessage("user", userInput));
        request.setMessages(messages);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth("sk-e05a60b1444f4522aa20bc07611294ba");
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 发送请求
        try {
            ResponseEntity<JsonNode> response = restTemplate.exchange(
                    API_URL,
                    HttpMethod.POST,
                    new HttpEntity<>(request, headers),
                    JsonNode.class
            );

            // 处理响应
            JsonNode body = response.getBody();
            String returnContent = body.get("choices").get(0).get("message").get("content").asText();
            // 保存到历史记录
            history.add(new ChatMessage("user", userInput));
            history.add(new ChatMessage("assistant", returnContent));

        } catch (Exception e) {
            history.add(new ChatMessage("system", "Error: " + e.getMessage()));
        }

        model.addAttribute("messages", history);
        return "chat";
    }
}

